package com.zhm.demo.duckdb.cfg;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {DuckDbCfg.BASE_PACKAGES}, sqlSessionFactoryRef = DuckDbCfg.SQL_SESSION_FACTORY_REF)
public class DuckDbCfg {

    public static final String BASE_PACKAGES = "com.zhm.demo.duckdb.mapper";
    public static final String SQL_SESSION_FACTORY_REF = "sqlSessionFactoryDuck";
    public static final String DATA_SOURCE_REF = "dataSourceDuck";
    public static final String XML_LOCAL = "classpath*:com/zhm/demo/duckdb/mapper/xml/*.xml";

    @Bean(name = DATA_SOURCE_REF)
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("org.duckdb.DuckDBDriver");//如果不配置druid会根据url自动识别dbType，然后选择相应的driverClassName
//        dataSource.setUrl("jdbc:duckdb:");
        dataSource.setUrl("jdbc:duckdb:/duckdb/duckdb.db"); // 文件模式
        return dataSource;

    }


    @Bean(name = SQL_SESSION_FACTORY_REF)
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        factoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(XML_LOCAL)
        );
        return factoryBean.getObject();
    }


}
